#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import requests
import json, sys

zabbix_api_path = '/api_jsonrpc.php'
web = 'https'

from loguru import logger
logger.add("/var/log/Task/Tasks.log", rotation="00:00", backtrace=True, diagnose=True, level="DEBUG")

# -------zabbix 登陆认证，获取token----
def zabbix_get_token(user, passwd, serverip):
    url = web + '://' + serverip + zabbix_api_path
    post_data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": user,
            "password": passwd
        },
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}

    ret = requests.post(url, data=json.dumps(post_data), headers=post_header)
    logger.info(ret.text)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        token = zabbix_ret.get('result')
    return token


# -------zabbix获取组信息--exsearch:0/1-------
def zabbix_get_group(token, serverip, search_type, search_name, exsearch):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": [
                "groupids",
                "name"],
            "search": {
                search_type: search_name
            },
            "excludeSearch": exsearch,
            "searchWildcardsEnabled": "true"
        },
        "id": 11,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    group_list = zabbix_ret.get('result')

    return group_list


# -------zabbix获取主机信息-id:12--------
def zabbix_get_hosts(token, serverip, filter_type, filter_host):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": [
                "hostid",
                "name",
                "interfaces"
                "status"
            ],
            "filter": {
                filter_type: [
                    filter_host
                ]
            }
        },
        "id": 12,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('查询' + filter_host + '结果:' + str(zabbix_ret['result']))
    return zabbix_ret


# -------zabbix获取主机信息2-id:13--------
def zabbix_get2_hosts(token, serverip, filter_type, filter_host):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": [
                "hostid",
                "name",
                "status"
            ],
            filter_type: filter_host
        },
        "id": 13,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)

    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
        sys.exit()
    else:
        hosts_list = zabbix_ret.get('result')
    return hosts_list


# -------zabbix获取模板信息-id:14--------
def zabbix_get_templates(token, serverip, filter_type, filter_host):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": [
                "hostid",
                "name",
                "status"],
            "search": {
                filter_type: [
                    filter_host
                ]
            },
            "excludeSearch": '0',
            "searchWildcardsEnabled": "true"
        },
        "id": 14,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    hosts_list = zabbix_ret.get('result')
    return hosts_list


# -------zabbix获取接口-id:15--------
def zabbix_get_hostinterface(token, serverip, hostids):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostinterface.get",
        "params": {
            "output": [
                "hostid",
                "interfaceid",
                "ip"],
            "hostids": hostids

        },
        "id": 15,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('查询' + hostids + '结果:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix获取自定义宏信息-id:16--------
def zabbix_get_macros(token, serverip, filter_type, filter_host):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "usermacro.get",
        "params": {
            "output": "extend",
            filter_type: filter_host
        },
        "id": 16,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('查询' + str(filter_host) + '结果:' + str(zabbix_ret['result']))
    return zabbix_ret


# -------zabbix获取告警信息-id:17--------
def zabbix_get_alerts(token, serverip, filter_type, filter_host):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "alert.get",
        "params": {
            "output": "extend",
            filter_type: filter_host
        },
        "id": 17,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('查询' + str(filter_host) + '结果:' + str(zabbix_ret['result']))
    return zabbix_ret['result']


# -------zabbix获取链接到模板的主机-id:18--------
def zabbix_get_template_info(token, serverip, filter_type, filter_host):
    # filter_type：https://www.zabbix.com/documentation/3.4/zh/manual/api/reference/template/get
    # 常用值：selectHosts, selectTemplates,
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": [
                "hostid",
                "name",
                "status"],
            "selectHosts": [
                "hostid",
            ],
            filter_type: filter_host
        },
        "id": 18,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('查询' + str(filter_host) + '结果:' + str(zabbix_ret['result']))
    return zabbix_ret['result']


# -------zabbix获取历史信息---------
def zabbix_get_history(token, serverip, itemids, time_from, time_till, limit):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "history.get",
        "params": {
            "output": "extend",
            "history": 3,
            "itemids": itemids,
            "sortfield": "clock",
            "sortorder": "DESC",
            "limit": limit,
        },
        "id": 11,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)

    return zabbix_ret


# --------zabbix 获取用户组信息--------
def zabbix_get_usergroup(token, serverip, search_type, search_name, exsearch):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "usergroup.get",
        "params": {
            "output": "extend",
            "search": {
                search_type: search_name
            },
            "selectRights": [
                "permission",
                "id"
            ],
            "excludeSearch": exsearch,
            "searchWildcardsEnabled": "true"
        },
        "id": 11,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    group_list = zabbix_ret.get('result')

    return group_list


# -------zabbix获取用户组信息--exsearch:0/1-------
def zabbix_search_info(token, serverip, option, search_type, search_name, exsearch):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": option + ".get",
        "params": {
            "search": {
                search_type: search_name
            },
            "excludeSearch": exsearch,
            "searchWildcardsEnabled": "true"
        },
        "id": 18,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    group_list = zabbix_ret.get('result')

    return group_list


# ---------zabbix创建简单主机-20------------
def zabbix_create_simple_host(token, serverip, hostip, hostname, descname, group_id, templateid, port_type, status):
    if port_type == 1:
        ports = "10050"
    elif port_type == 2:
        ports = "161"
    else:
        logger.info("port_type error:端口类型未识别:" + str(port_type))
        return 'error:port_type error'

    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostname,
            "name": descname,
            "interfaces": [
                {
                    "type": port_type,
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": ports
                }
            ],
            "groups": [
                {
                    "groupid": group_id
                }
            ],
            "templates": [
                {
                    "templateid": templateid
                }
            ],
            "status": status
        },
        "auth": token,
        "id": 21
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('新建' + hostname + '结果:' + str(zabbix_ret['result']))

    return zabbix_ret


# ---------zabbix创建主机-21------------
def zabbix_create_host(token, serverip, hostip, hostname, group_id, templateid, port_type, macros, inventory, tags,
                       status):
    if port_type == 1:
        ports = "10050"
    elif port_type == 2:
        ports = "161"
    else:
        logger.info("port_type error:端口类型未识别:" + str(port_type))
        return 'error:port_type error'
    # 判断group_id类型，string or list
    group_list = []
    if isinstance(group_id, list):
        for gid in group_id:
            group_list.append({"groupid": gid})
    else:
        group_list.append({"groupid": group_id})
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostname,
            "interfaces": [
                {
                    "type": port_type,
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": ports
                }
            ],
            "groups": group_list,
            "templates": [
                {
                    "templateid": templateid
                }
            ],
            "macros": macros,
            "inventory_mode": 1,
            "inventory": inventory,
            "tags": tags,
            "status": status
        },
        "auth": token,
        "id": 21
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    logger.info(json.dumps(zabbix_ret))
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('新建' + hostname + '结果:' + str(zabbix_ret['result']))

    return zabbix_ret


# ---------zabbix创建主机(用于线路监控)-29------------
def zabbix_create_line(token, serverip, hostip, hostname, name, groups, templateid, port_type, macros, inventory, tags,
                       status):
    if port_type == "1":
        ports = "10050"
    elif port_type == "2":
        ports = "161"
    else:
        logger.info("port_type error:端口类型未识别")

    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostname,
            "name": name,
            "interfaces": [
                {
                    "type": port_type,
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": ports
                }
            ],
            "groups": groups,
            "templates": [
                {
                    "templateid": templateid
                }
            ],
            "macros": macros,
            "inventory_mode": 1,
            "inventory": inventory,
            "tags": tags,
            "status": status
        },
        "auth": token,
        "id": 29
    }

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info(json.dumps(zabbix_ret))
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Line' + name + '创建成功!')
    return zabbix_ret


# ---------zabbix创建主机组-22--------------------
def zabbix_create_group(token, serverip, group_name):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.create",
        "params": {
            "name": group_name
        },
        "auth": token,
        "id": 22
    }

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Group' + group_name + '创建成功!')
    return zabbix_ret


# ---------zabbix创建主机组-22--------------------
def zabbix_create_user(token, serverip, username, groupid):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "user.create",
        "params": {
            "alias": username,
            "usrgrps": [
                {
                    "usrgrpid": groupid  # 22:PMO Read ;21:Network Read
                }
            ],
        },
        "auth": token,
        "id": 22
    }

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('user' + username + '创建成功!')
    return zabbix_ret


# ---------zabbix创建空模板-id:23--------------------
def zabbix_create_template(token, serverip, group_id, template_name):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.create",
        "params": {
            "host": template_name,
            "groups": {
                "groupid": group_id
            },
        },
        "auth": token,
        "id": 23
    }

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    template_info = zabbix_ret.get('result')
    return template_info


# ---------zabbix创建自动发现规则---25---------------
def zabbix_create_dis_rule(token, serverip, iprange, group_name, dchecks):
    if dchecks == "9":
        dkey = "system.uname"
        ports = "10050"
    elif dchecks == "11":
        dkey = "sysName.0"
        ports = "161"
    else:
        logger.info("dchecks error:检查类型未识别")
    url = 'http://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "drule.create",
        "params": {
            "name": group_name,
            "iprange": iprange,
            "dchecks": [
                {
                    "type": dchecks,
                    "key_": dkey,
                    "snmp_community": "{$SNMP_COMMUNITY}",
                    "ports": ports,
                    "uniq": "1",
                    "host_source": "3",
                    "name_source": "3"
                }
            ]
        },
        "auth": token,
        "id": 4
    }

    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    logger.info(ret)


# ---------zabbix创建维护期间---26---------------
def zabbix_create_maintenance(token, serverip, maintenance_name, active_since, active_till, host_type, hosts_ids,
                              timeperiods):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "maintenance.create",
        "params": {
            "name": maintenance_name,
            "active_since": active_since,  # 开始时间
            "active_till": active_till,  # 结束时间
            host_type: hosts_ids,  # groupids/hostids : hosts_ids(list)
            "timeperiods": timeperiods,
        },
        "auth": token,
        "id": 26
    }
    logger.info(get_data)
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    return zabbix_ret


# -------zabbix更新主机信息 id 31---------
def zabbix_update_host(token, serverip, hostid, update_type, update_value):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.update",
        "params": {
            "hostid": hostid,
            update_type: update_value
        },
        "id": 31,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + hostid + '更新成功')
    return zabbix_ret


# -------zabbix更新组信息 id 32---------
def zabbix_update_group(token, serverip, groupid, update_type, update_value):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.update",
        "params": {
            "groupid": groupid,
            update_type: update_value
        },
        "id": 32,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    ret_list = zabbix_ret.get('result')
    return ret_list


# ---------zabbix更新线路(用于线路监控)-33------------
def zabbix_update_line(token, serverip, hostid, hostip, hostname, name, groups, templateid, port_type, macros,
                       inventory, tags, status):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.update",
        "params": {
            "hostid": hostid,
            "host": hostname,
            "name": name,
            "groups": groups,
            "templates": [
                {
                    "templateid": templateid
                }
            ],
            "macros": macros,
            "inventory_mode": 1,
            "inventory": inventory,
            "tags": tags,
            "status": status

        },
        "auth": token,
        "id": 33
    }

    post_header = {'Content-Type': 'application/json'}
    logger.info(json.dumps(get_data))
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('host' + name + '更新成功')
    return zabbix_ret


# -------zabbix更新接口-id:34--------
def zabbix_uptade_hostinterface(token, serverip, interfaceid, ip):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostinterface.update",
        "params": {
            "interfaceid": interfaceid,
            "ip": ip
        },
        "id": 34,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('接口' + interfaceid + '已更新:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix更新用户组信息---------
def zabbix_update_usergroup(token, serverip, usrgrpid, rights):
    '''
    :param token:
    :param serverip:
    :param groupid: 站点id
    :param rights: 用户组权限 'rights': [{'permission': '2', 'id': '477'}]
    :param permission:
        0 - access denied;
        2 - read-only access;
        3 - read-write access.
    :return:
    '''
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "usergroup.update",
        "params": {
            "usrgrpid": usrgrpid,
            "rights": rights
        },
        "auth": token,
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if zabbix_ret.get('result'):
        group_list = zabbix_ret.get('result')
    else:
        group_list = zabbix_ret
    return group_list


# -------zabbix删除host id：41--------
def zabbix_hosts_delete(token, serverip, hostids):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "host.delete",
        "params": hostids,
        "id": 41,
        "auth": token
    }

    post_header = {'Content-Type': 'application/json'}
    # print(str(json.dumps(get_data)))
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已删除:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix主机组添加主机--id：51------
def zabbix_hostgroup_massadd(token, serverip, groupid, hostids):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.massadd",
        "params": {
            "groups": [
                {
                    "groupid": groupid,
                }
            ],
            "hosts": hostids,
        },
        "id": 51,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已添加到组:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix主机组查找主机--id：54------
def zabbix_hostgroup_get(token, serverip, group_name):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": "extend",
            "selectHosts": [
                'hostid',
            ],
            "filter": {
                "name": [
                    group_name,
                ]
            }
        },
        "id": 54,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Hostgroup' + str(group_name) + '发现hosts:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix移除模板--id：52------
def zabbix_template_massremove(token, serverip, templateids, hostids):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.massremove",
        "params": {
            "templateids_link": templateids,
            "hosts": hostids,
        },
        "id": 52,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已添加到组:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix移除主机组内主机--id：52------
def zabbix_hostgroup_massremove(token, serverip, groupids, hostids):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.massremove",
        "params": {
            "groupids": [
                groupids,  # str
            ],
            "hostids": hostids,  # list
        },
        "id": 52,
        "auth": token
    }
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已从组中移除:' + str(zabbix_ret['result']))

    return zabbix_ret


# -------zabbix关联模板--id：53------
def zabbix_template_massadd(token, serverip, templateid, hostids):
    url = web + '://' + serverip + zabbix_api_path
    get_data = {
        "jsonrpc": "2.0",
        "method": "template.massadd",
        "params": {
            "templates": [
                {
                    "templateid": templateid,
                }
            ],
            "hosts": hostids,
        },
        "id": 53,
        "auth": token
    }
    logger.info(get_data)
    post_header = {'Content-Type': 'application/json'}
    ret = requests.post(url, data=json.dumps(get_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    if 'error' in zabbix_ret:
        error = zabbix_ret.get('error')
        logger.info('error:' + error['message'] + ' ' + error['data'])
    elif 'result' in zabbix_ret:
        logger.info('Host' + str(hostids) + '已关联到模板:' + str(zabbix_ret['result']))

    return zabbix_ret
